package com.soundShape.mediators.comparison
{
	
	import com.soundShape.events.SoundShapeEvent;
	import com.soundShape.itemRenderers.ComparisonThumbnail;
	import com.soundShape.mediators.AbstractViewMediator;
	import com.soundShape.popUps.ComparisonPhotos;
	import com.soundShape.utils.StringUtils;
	import com.soundShape.utils.ThumbnailCreator;
	import com.soundShape.views.comparison.Comparison;
	import com.soundShape.vo.CustomerVO;
	import com.soundShape.vo.PhotoVO;
	import com.soundShape.vo.TreatmentVO;
	
	import flash.events.MouseEvent;
	
	import mx.binding.utils.BindingUtils;
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.controls.ComboBox;
	import mx.controls.DataGrid;
	import mx.events.ListEvent;
	import mx.managers.PopUpManager;
	import mx.utils.ObjectUtil;
	
	import nz.co.codec.flexorm.criteria.Criteria;
	
	
	
	
	public class ComparisonMediator extends AbstractViewMediator
	{
		
	
		private var treatmentVO1:TreatmentVO;
		private var treatmentVO2:TreatmentVO;
				
				public function ComparisonMediator()
				{
					super(Comparison);
				}
				
				/**
				 * Since the AbstractViewMediator sets the view via Autowiring in Swiz,
				 * we need to create a local getter to access the underlying, expected view
				 * class type.
				 */
				public function get view():Comparison
				{
					return this._view as Comparison;
				}
				
				/**
				 * The <code>init()</code> method is fired off automatically by the 
				 * AbstractViewMediator when the creation complete event fires for the
				 * corresponding ViewMediator's view. This allows us to listen for events
				 * and set data bindings on the view with the confidence that our view
				 * and all of it's child views have been created and live on the stage.
				 */
				override protected function init():void
				{
					super.init();
					
					this.setViews();
					
				}
				
				override protected function setViewDataBindings():void
				{
					super.setViewDataBindings();
					BindingUtils.bindProperty(this.view.cmbxCustomers,"dataProvider",this.applicationModel.customers,"source");
					setCustomerComboBox();
					
				}	
				
				override protected function setViewListeners():void
				{
					super.setViewListeners();
					
					this.view.btnMenu.addEventListener(MouseEvent.CLICK, handleBtnMenu);
					
					this.view.cmbxCustomers.addEventListener(ListEvent.CHANGE, handleCmbxCustomersChange);
					
					this.view.btnDoComparison.addEventListener(MouseEvent.CLICK, handleBtnDoComparison);
					
					this.view.dgTreatments1.addEventListener(ListEvent.ITEM_CLICK, handleListItemClick);
					
					this.view.dgTreatments2.addEventListener(ListEvent.ITEM_CLICK, handleListItemClick);
					
					this.view.lstImg1.addEventListener(SoundShapeEvent.IMAGE_SELECTED, handleImageSelected);
					
					this.view.lstImg2.addEventListener(SoundShapeEvent.IMAGE_SELECTED, handleImageSelected);
					
					this.view.imgRefresh.addEventListener(MouseEvent.CLICK, handleImgRefreshClick);
				}
				
				private function setViews():void
				{
					doClearComparison();
					doClearDataGrids();
					resetPanelTitle();
					this.view.imgRefresh.enabled = false;
				}
				
				
				/**
				 * *******************************************************************************
				 * Handlers
				 * *******************************************************************************
				 */
				private function handleBtnMenu(mouseEvent:MouseEvent):void
				{
					this.dispatcher.dispatchEvent(new SoundShapeEvent(SoundShapeEvent.SWITCH_TO_MENU_VIEW));
				}
				
				
				private function handleCmbxCustomersChange(listEvent:ListEvent=null):void
				{
					
					if(listEvent != null)
						this.applicationModel.customerVO = ComboBox(listEvent.currentTarget).selectedItem as CustomerVO;
					
					this.view.imgRefresh.enabled = true;
					
					//clean out any existing customer data
					if(this.view.lstImg1.dataProvider != null || this.view.lstImg2.dataProvider != null)
					{
						ArrayCollection(this.view.lstImg1.dataProvider).removeAll(); ArrayCollection(this.view.lstImg1.dataProvider).refresh();
						ArrayCollection(this.view.lstImg2.dataProvider).removeAll(); ArrayCollection(this.view.lstImg2.dataProvider).refresh();
					}
					
					var soundShapeEvent:SoundShapeEvent = new SoundShapeEvent(SoundShapeEvent.GET_TREATMENTS_COMPARISON);
					soundShapeEvent.data = this.applicationModel.customerVO.id;
					
					this.dispatcher.dispatchEvent(soundShapeEvent);
					
					this.resetPanelTitle();
				}
				
				private function handleBtnDoComparison(mouseEvent:MouseEvent):void
				{
					var currentButtonLabel:String = this.view.btnDoComparison.label;
					
					//clear an existing comparison
					if(currentButtonLabel == "clear comparison")
					{
						doClearComparison();
						doClearDataGrids();
						resetPanelTitle();
						return;
					}
					
					
					var criteria:Criteria;
					var photoVOs:ArrayCollection;
					var thumbnailCreator:ThumbnailCreator;
					
					/*if(treatmentVO1.id == treatmentVO2.id)
					{
						Alert.show("You cannot do comparisons\non the same treatment", "Error");
						return;
					}*/
					
					//get photos for first treatment
					criteria = this.applicationModel.entityManager.createCriteria(PhotoVO);
					criteria.addEqualsCondition("treatmentID",treatmentVO1.id);
					criteria.addEqualsCondition("type","before");
					photoVOs = this.applicationModel.entityManager.fetchCriteria(criteria);
					
					//progress indicator
					this.view.swfLdrProgressBefore.visible = true;
					
					if(photoVOs.length == 0)
					{
						Alert.show("This treatment\nid: " + treatmentVO1.id + "\nhas NO associated photos", "Fatal error");
						this.view.swfLdrProgressBefore.visible = false;
						return;
					}
					
					//create thumbnails
					thumbnailCreator = new ThumbnailCreator();
					thumbnailCreator.createThumbnails(photoVOs, callback1);
					
					//get photos for subsequent treatment
					criteria = this.applicationModel.entityManager.createCriteria(PhotoVO);
					criteria.addEqualsCondition("treatmentID",treatmentVO2.id);
					criteria.addEqualsCondition("type","after");
					photoVOs = this.applicationModel.entityManager.fetchCriteria(criteria);
					
					//progress indicator
					this.view.swfLdrProgressAfter.visible = true;
					
					if(photoVOs.length == 0)
					{
						Alert.show("This treatment\nid: " + treatmentVO2.id + "\nhas NO associated photos", "Fatal error");
						this.view.swfLdrProgressAfter.visible = false;
						return;
					}
					
					//create thumbnails
					thumbnailCreator = new ThumbnailCreator();
					thumbnailCreator.createThumbnails(photoVOs, callback2);
					
					//set new label to 'do comparison' button
					this.view.btnDoComparison.label = "clear comparison";
				}
				
				private function callback1(imgBitmaps:Array):void
				{
					this.view.lstImg1.dataProvider = new ArrayCollection(imgBitmaps);
					this.view.swfLdrProgressBefore.visible = false;
				}
				
				private function callback2(imgBitmaps:Array):void
				{
					this.view.lstImg2.dataProvider = new ArrayCollection(imgBitmaps);
					this.view.swfLdrProgressAfter.visible = false;
				}
				
				
				private function handleListItemClick(listEvent:ListEvent):void
				{
					
					var treatmentVO:TreatmentVO = ArrayCollection(DataGrid(listEvent.currentTarget).dataProvider).getItemAt(listEvent.rowIndex) as TreatmentVO;
					
					switch(DataGrid(listEvent.currentTarget).id)
					{
						case "dgTreatments1":
							this.treatmentVO1 = treatmentVO;
							this.view.pnlBefore.title = "Before Photos: " + setPanelTitle(treatmentVO1);
							break;
						
						case "dgTreatments2":
							this.treatmentVO2 = treatmentVO;
							this.view.pnlAfter.title = "After Photos: " + setPanelTitle(treatmentVO2);
							break;
					}
				}
				
				private var comparisonThumbnail_0:ComparisonThumbnail;
				private var comparisonThumbnail_1:ComparisonThumbnail;
				
				protected function handleImageSelected(soundShapeEvent:SoundShapeEvent):void
				{
					if(comparisonThumbnail_0 == null)
						comparisonThumbnail_0 = soundShapeEvent.data;
					else if (comparisonThumbnail_1 == null)
						comparisonThumbnail_1 = soundShapeEvent.data;
					
					
					if(comparisonThumbnail_0 != null && comparisonThumbnail_1 != null)
						doComparisonPhoto(comparisonThumbnail_0, comparisonThumbnail_1);
					
					/**/
				}
				
				protected function doComparisonPhoto(comparisonThumbnail_0:ComparisonThumbnail, comparisonThumbnail_1:ComparisonThumbnail):void
				{
					var comparisonPhotos:ComparisonPhotos = new ComparisonPhotos();
					comparisonPhotos.bitmap0 = comparisonThumbnail_0._bitmap;
					comparisonPhotos.bitmap1 = comparisonThumbnail_1._bitmap;
					comparisonPhotos.callback = resetThumbnailBorders;
					PopUpManager.addPopUp(comparisonPhotos,this.view,true);
					PopUpManager.centerPopUp(comparisonPhotos);
				}
				
				protected function doClearComparison():void
				{
					try
					{
						ArrayCollection(this.view.lstImg1.dataProvider).removeAll(); ArrayCollection(this.view.lstImg1.dataProvider).refresh();
						ArrayCollection(this.view.lstImg2.dataProvider).removeAll(); ArrayCollection(this.view.lstImg2.dataProvider).refresh();
						comparisonThumbnail_0 = null;
						comparisonThumbnail_1 = null;
						this.view.btnDoComparison.label = "do comparsion";
					}
					catch(e:Error)
					{
						trace("Error during doClearComparison()");
					}
				}
				
				protected function doClearDataGrids():void
				{
					try
					{
						ArrayCollection(this.view.dgTreatments1.dataProvider).removeAll(); ArrayCollection(this.view.dgTreatments1.dataProvider).refresh();
						ArrayCollection(this.view.dgTreatments2.dataProvider).removeAll(); ArrayCollection(this.view.dgTreatments1.dataProvider).refresh();
					}
					catch(e:Error)
					{
						trace("Error during doClearDataGrids()");
					}	
				}
				
				protected function resetThumbnailBorders():void
				{
					comparisonThumbnail_0.isClick = false;
					comparisonThumbnail_1.isClick = false;
					comparisonThumbnail_0 = null;
					comparisonThumbnail_1 = null;
				}
				
				
				protected function handleImgRefreshClick(mouseEvent:MouseEvent):void
				{
					handleCmbxCustomersChange();
				}
				
				/**
				 * *******************************************************************************
				 * Swiz EventHanders
				 * *******************************************************************************
				 */
				[EventHandler(event="SoundShapeEvent.SET_TREATMENTS_COMPARISON")]
				public function setTreatmentsPhoto(soundShapeEvent:SoundShapeEvent):void
				{
					this.view.dgTreatments1.dataProvider = soundShapeEvent.data;
					this.view.dgTreatments2.dataProvider =  soundShapeEvent.data;
				}
				
				/**
				 * *******************************************************************************
				 * util
				 * *******************************************************************************
				 */
				private function setCustomerComboBox():void
				{
					this.view.cmbxCustomers.selectedIndex = -1;
					/*if(this.applicationModel.customerVO != null)
					{
						this.view.cmbxCustomers.selectedIndex = (this.view.cmbxCustomers.dataProvider as ArrayCollection).getItemIndex(this.applicationModel.customerVO);
					}
					else
					{
						this.view.cmbxCustomers.selectedIndex = -1;
					}*/
				}
				
				
				private function setPanelTitle(treatmentVO:TreatmentVO):String
				{
					var rTitle:String = "";
					rTitle += treatmentVO.customer;
					rTitle += " ";
					rTitle += StringUtils.doDateParse(treatmentVO.treatmentDate);
					rTitle += " ";
					rTitle += StringUtils.doTimeParse(treatmentVO.treatmentDate);
				return rTitle;
				}
				
				private function resetPanelTitle():void
				{
					this.view.pnlBefore.title = "Before Photos: ";
					this.view.pnlAfter.title = "After Photos: ";
				}
				
			
		}
		
	}
